function [ frames ] = framing_with_class( label, data, header )
%FRAMING_WITH_CLASS Summary of this function goes here
%   Detailed explanation goes here

frames = framing(data, header);
frames(2,1:end-1) = frames(2,2:end);
sample_rate = header{1}.sample_rate;

% combine labels into one sorted list
combined_lbl = zeros(3, 0);
for i=1:length(label)
    left_limits = label{i}.region(1:2:end);
    right_limits = label{i}.region(2:2:end);
    tmp_clbl = [left_limits;right_limits;ones(size(left_limits)).*i];
    combined_lbl = [combined_lbl tmp_clbl];
end

[left_limits, left_idx] = sort(combined_lbl(1, :));
[right_limits, right_idx] = sort(combined_lbl(2, :));
if any(left_idx ~= right_idx)
    error('Label not consistent. There is overlaping.');
end
combined_lbl = [left_limits; right_limits; combined_lbl(3, left_idx)];

% eliminating overlaping
for i=2:size(combined_lbl, 2)
    combined_lbl(1, i) = max(combined_lbl(2, i-1), combined_lbl(1, i));
end

classes = zeros(1, size(frames, 2));
for i=1:size(frames, 2)
    first_sample_time = data(frames(1, i), 1);
    last_sample_time = data(frames(2, i), 1);
    tmp_lbl = find(combined_lbl(2, :) > last_sample_time, 1, 'first');
    if ~isempty(tmp_lbl) && first_sample_time > combined_lbl(1, tmp_lbl)
        classes(i) = combined_lbl(3, tmp_lbl);
    end
end

frames = [frames; classes];

end

